# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import os
import json
import codecs
import MySQLdb


class YuSpiderPipeline(object):

    def __init__(self):
        if not os.path.exists('data'):
            os.makedirs('data')
        self.file = codecs.open('data/dysk.json', 'w', encoding='utf-8')

    def process_item(self, item, spider):
        line = json.dumps(dict(item), ensure_ascii=False) + "\n"
        self.file.write(line)
        return item

    def spider_closed(self, spider):
        self.file.close()


class MySqlPipeline(object):

    def __init__(self):
        pass

    def process_item(self, item, spider):
        conn = MySQLdb.connect('localhost', 'root', 'admin8023', 'chiakiyu')
        cur = conn.cursor()
        cur.execute('insert into hehe values(%s)', item)
        conn.commit()
        cur.close()
        conn.close()

        return item

    def spider_closed(self, spider):
        pass
